package ucd.csi.comp30220.fall2011.oteop.collision;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;

import javax.naming.NamingException;
import org.exolab.jms.persistence.PersistenceException;
import org.exolab.jms.server.JmsServer;
import org.exolab.jms.service.ServiceException;
import org.exolab.jms.tools.db.DBTool;

/**
 * Starts the OpenJMS Server and initialises a derby database if there is not one already defined
 * This needs to be run for collision detection to work.
 * @author David Haddock
 *
 */
public class JmsSession {
    
	public JmsSession(int tcpPort, int jndiPort) throws Exception
	{
		 System.setProperty("openjms.home", new File("./openjms").getCanonicalPath());
		 BufferedReader reader = new BufferedReader(new FileReader("./openjms/config/openjms.xml.tagged"));
		 PrintWriter writer = new PrintWriter(new FileOutputStream("./openjms/config/openjms.xml"));
		 for (String line; (line = reader.readLine()) != null; ) {
		     line = line.replaceAll("TCP_PORT", "" +tcpPort);
		     line = line.replaceAll("JNDI_PORT", "" +jndiPort);
		     writer.println(line);
		 }
		 writer.flush();
		 
		 File file = new File("./openjms/config/openjms.xml");
 
		 DBTool dbtool = new DBTool(file.getCanonicalPath());
		 try {
			 dbtool.create(); 
		 }
		 catch(PersistenceException e) {
			 System.out.println("database already created");
		 }

		 JmsServer server =  new JmsServer(file.getCanonicalPath());
		 server.init();
	}
}